import 'dart:io';

import 'package:app/common/colors.dart';
import 'package:app/services/dio_manager.dart';
import 'package:app/utils/uint.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:qiniu_flutter_sdk/qiniu_flutter_sdk.dart';

class ManageFacePage extends StatefulWidget {
  @override
  _ManageFacePageState createState() => _ManageFacePageState();
}

class _ManageFacePageState extends State<ManageFacePage>
    with TickerProviderStateMixin {

  _ManageFacePageState() : storage = Storage();

  // 用户输入的文件名
  String? key;

  // 用户输入的 partSize
  int partSize = 4;

  // 用户输入的 token
  String? token;

  String? qiniu_image_path, qiniu_image_path1, qiniu_image_path2;
  bool isShowImage = false;
  bool isShowImage1 = false;
  bool isShowImage2 = false;

  bool isShowButton = false;

  /// storage 实例
  final Storage storage;

  /// 当前选择的文件
  PlatformFile? selectedFile;



  // 控制器，可以用于取消项目、获取上述的状态，进度等信息
  PutController? putController;

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            leading: IconButton(
              onPressed: () {
                Get.back();
              },
              icon: Image.asset(
                'images/leftarr.png',
                color: Colors.white,
                width: 15,
                height: 15,
              ),
            ),
            title: const Text(
              '实名信息',
              style: TextStyle(
                color: Colors.white,
              ),
            ),
            backgroundColor: AppColor.themeColor), // 就是这里
        body: Container(
            color: Colors.white,
            padding: const EdgeInsets.all(5.0),
            child: Column(
              children: <Widget>[
                Expanded(
                  child: GestureDetector(
                    onTap: () {
                      if (isShowImage) {
                        ImagePickers.previewImage(qiniu_image_path!);
                      } else {
                        openSelectFileWindow(0);
                      }
                    },
                    child: Container(
                      padding: const EdgeInsets.all(5.0),
                      child: Center(
                        child: isShowImage
                            ? Image.network(qiniu_image_path!,
                                width: 240, height: 150, fit: BoxFit.fill)
                            : Image.asset('images/accust0.png',
                                width: 240, height: 150),
                      ),
                    ),
                  ),
                ),
                Expanded(
                  child: GestureDetector(
                    onTap: () {
                      if (isShowImage1) {
                        ImagePickers.previewImage(qiniu_image_path1!);
                      } else {
                        openSelectFileWindow(1);
                      }
                    },
                    child: Container(
                      padding: const EdgeInsets.all(5.0),
                      child: Center(
                        child: isShowImage1
                            ? Image.network(qiniu_image_path1!,
                                width: 240, height: 150, fit: BoxFit.fill)
                            : Image.asset('images/accust1.png',
                                width: 240, height: 150),
                      ),
                    ),
                  ),
                ),
                Expanded(
                  child: GestureDetector(
                    onTap: () {
                      if (isShowImage2) {
                        ImagePickers.previewImage(qiniu_image_path2!);
                      } else {
                        openSelectFileWindow(2);
                      }
                    },
                    child: Container(
                      padding: const EdgeInsets.all(5.0),
                      child: Center(
                        child: isShowImage2
                            ? Image.network(qiniu_image_path2!,
                                width: 240, height: 150, fit: BoxFit.fill)
                            : Image.asset('images/accust2.png',
                                width: 240, height: 150),
                      ),
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    color: Colors.white,
                    padding: const EdgeInsets.all(5.0),
                    child: Center(
                      child: Container(
                        margin:
                            const EdgeInsets.only(top: 62, right: 15, left: 15),
                        width: Get.width,
                        height: 45,
                        child: Visibility(
                            visible: isShowButton,
                            child: MaterialButton(
                              elevation: 0,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(22),
                              ),
                              color: AppColor.themeColor,
                              onPressed: () {
                                BotToast.showLoading(clickClose: true);
                                Future.delayed(Duration(seconds: 3), () {
                                  BotToast.closeAllLoading();
                                  BotToast.showText(text: "上传认证成功");
                                  setState(() {
                                    isShowButton = false;
                                  });
                                });
                              },
                              child: Text(
                                '上传认证'.tr,
                                style: const TextStyle(color: Colors.white),
                              ),
                            )),
                      ),
                    ),
                  ),
                )
              ],
            )));
  }

  Future<void> openSelectFileWindow(int position) async {
    final fileResult =
        await FilePicker.platform.pickFiles(allowMultiple: false);
    if (fileResult != null) {
      PlatformFile file = fileResult.files.first;
      print('选中文件: ${file.path}');
      // ignore: unnecessary_null_comparison
      if (file.size != null) {
        // 一般在非 web 平台上可以直接读取 size 属性
        print('文件尺寸：${humanizeFileSize(file.size.toDouble())}');
      } else if (file.bytes != null) {
        print('文件尺寸：${humanizeFileSize(file.bytes!.length.toDouble())}');
      }

      setState(() {
        print('设置 selectedFile');
        selectedFile = file;
        startUpload(position);
      });
    }
  }

  void startUpload(int index) {
    print('创建 PutController');
    putController = PutController();

    var usedToken = token;

    if (usedToken == null || usedToken == '') {
      print('token 不能为空');
      return;
    }

    print('------------------------');

    if (selectedFile == null) {
      print('请选择文件');
      return;
    }

    print('开始上传文件');

    final putOptions = PutOptions(
      key: key,
      partSize: partSize,
      controller: putController,
    );
    Future<PutResponse> upload;
    if (kIsWeb) {
      upload = storage.putBytes(
        selectedFile!.bytes!,
        usedToken,
        options: putOptions,
      );
    } else {
      upload = storage.putFile(
        File(selectedFile!.path!),
        usedToken,
        options: putOptions,
      );
    }

    upload
      ..then((PutResponse response) {
        Map<String, dynamic> rawData = response.rawData;
        String hamstring = rawData["hash"];

        print('===>>>>$qiniu_image_path');

        setState(() {
          if (index == 0) {
            isShowImage = true;
            print('$qiniu_image_path');
          } else if (index == 1) {
            isShowImage1 = true;
            print('$qiniu_image_path1');
          } else {
            isShowImage2 = true;
            print('$qiniu_image_path2');
          }
          isShowButton = isShowImage && isShowImage1 && isShowImage2;
          print('------------------------');
        });
      })
      ..catchError((dynamic error) {
        if (error is StorageError) {
          switch (error.type) {
            case StorageErrorType.CONNECT_TIMEOUT:
              print('发生错误: 连接超时');
              break;
            case StorageErrorType.SEND_TIMEOUT:
              print('发生错误: 发送数据超时');
              break;
            case StorageErrorType.RECEIVE_TIMEOUT:
              print('发生错误: 响应数据超时');
              break;
            case StorageErrorType.RESPONSE:
              print('发生错误: ${error.message}');
              break;
            case StorageErrorType.CANCEL:
              print('发生错误: 请求取消');
              break;
            case StorageErrorType.UNKNOWN:
              print('发生错误: 未知错误');
              break;
            case StorageErrorType.NO_AVAILABLE_HOST:
              print('发生错误: 无可用 Host');
              break;
            case StorageErrorType.IN_PROGRESS:
              print('发生错误: 已在队列中');
              break;
          }
        } else {
          print('发生错误: ${error.toString()}');
        }

        print('------------------------');
      });
  }
}
